<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="品种" prop="breedId">
        <el-select  v-model="queryParams.breedId" placeholder="请选择品种" clearable class="!w-240px">
          <el-option
            v-for="variety in varietys" 
            :key="variety.id"
            :label="variety.name"
            :value="variety.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="供苗厂家" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入供苗厂家"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进苗日期" prop="inTime">
        <el-date-picker
          v-model="queryParams.inTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['farm:pc:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['farm:pc:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      highlight-current-row
      @row-click="handleCurrentChange"
       ref="tableRef"
    >
      <el-table-column label="序号" type="index" align="center" key="id" prop="id" width="60"/>
      <el-table-column label="品种" align="center" prop="breedName" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="供苗厂家" align="center" prop="manufacturer" />
      <el-table-column label="进苗总数" align="center" prop="totalNum" />
      <el-table-column label="剩余数量" align="center" prop="num" />
      <el-table-column label="进苗日期" align="center" prop="inTime" :formatter="dateFormatter2"/>
      <el-table-column label="当前日龄" align="center" prop="dayAge" />
      <el-table-column label="当前周龄" align="center" prop="weekAge" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" fixed="right" align="center" :show-overflow-tooltip="true" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['farm:pc:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['farm:pc:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PcForm ref="formRef" @success="getList" />
  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs v-model="activeHouse" @tab-change="handleClick">
      <el-tab-pane
        v-for="item in getStrDictOptions(DICT_TYPE.FARM_FARMHOUSE_TYPE)" :key="item.value" 
        :label="item.label" :value="item.value"
      >
        <InFarmhouseList
         :type="item.value" 
         :type-name="item.label" 
         :pc-id="currentRow ? currentRow.id : null"
         :active-house="activeHouse"
         ref="childGetListRef"   
         
        />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup lang="ts">
import { getIntDictOptions,getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { PcApi, PcVO } from '@/api/farm/pc'
import PcForm from './PcForm.vue'
import InFarmhouseList from './components/InFarmhouseList.vue'
import { func } from 'vue-types'
import { nextTick } from 'vue';

/** 批次 列表 */
defineOptions({ name: 'Pc' })

// 属性
// const dictData =getStrDictOptions(DICT_TYPE.FARM_FARMHOUSE_TYPE)
// console.log(dictData,'dictData');

// 品种
const varietys =ref([])
const childGetListRef =ref<any>(null)//子组件方法

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
/** 选中行操作 */
const currentRow = ref({}) // 选中行
const currentRowId = ref(0); // 表格组件的引用
const loading = ref(true) // 列表的加载中
const list = ref<PcVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  breedId: undefined,
  name: undefined,
  manufacturer: undefined,
  inTime: [],
  status: undefined,
  createTime: [],
  dayAge:undefined,
  weekAge:undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const activeHouse = ref<string>('0')
// 默认选中第一条

const tableRef = ref<any>(null) // 表格组件的引用


// 方法
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PcApi.getPcPage(queryParams)
    // console.log(queryParams,'queryParams');
    list.value = data.list as PcVO[]
    total.value = data.total

    // 计算当前日龄和周龄
    // 1.先获取当前时间’
    const currentDate = new Date()
    // console.log(currentDate,'currentDate');
    // 2.遍历数据，计算日龄和周龄
    list.value.forEach(item =>{
      const inTime =new Date(item.inTime) //将进苗日期转成日期对象
      const timeDiff = currentDate.getTime() - inTime.getTime(); //计算时间
      const dayAgeData = Math.floor(timeDiff / (1000 * 60 * 60 * 24));//计算天数
      const weekAgeData =Math.floor(dayAgeData / 7 + 1);

      // 3.将所得的日龄和周龄渲染到页面上
      item.dayAge = dayAgeData
      item.weekAge = weekAgeData

    })
    
   
    //默认选择第一条 
    if(list.value.length > 0){
      currentRowId.value = list.value[0].id; // 默认选择第一条数据的id

      currentRow.value = list.value[0]

      if(tableRef.value){
        tableRef.value.setCurrentRow(list.value[0]) // 设置当前行
      }else{
        console.error('tableRef is null');
      }
    }else{
      currentRow.value = {}
    }

  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()//重置表单的字段和状态
  activeHouse.value = '0'; // 重置 tabs
  currentRow.value = {}; // 重置 currentRow
  handleQuery()
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PcApi.deletePc(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PcApi.exportPc(queryParams)
    download.excel(data, '批次.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleCurrentChange = (row) => {
  currentRow.value = row
  // console.log(currentRow.value,'currentRow.value');
}

// 切换不同屋舍类型
const handleClick=(tab:string)=>{
  console.log(tab,'tab');
  activeHouse.value =tab

  if(childGetListRef.value){
    childGetListRef.value.refreshTable()
  }
}

// 选择品种
const getVariety =() =>{
  PcApi.getVarietyApi().then(res=>{
    // console.log(res,'res');
     varietys.value =res
  })
}


/** 初始化 **/
onMounted(() => {
  getList()
  getVariety()
})

</script>